/**
 * 创建初始管理员用户脚本
 * 使用方法: npx ts-node scripts/createAdmin.ts
 */

import { initMySQL } from '../src/database/mysql';
import { hashPassword } from '../src/utils/password';
import { utils } from '../src/utils/utils';
import { query, queryOne } from '../src/database/mysql';
import { User } from '../src/database/models';

async function createAdmin() {
  try {
    initMySQL();
    
    const username = process.argv[2] || 'admin';
    const password = process.argv[3] || 'admin123';
    
    // 检查用户是否已存在
    const existing = await queryOne<User>('SELECT * FROM users WHERE username = ?', [username]);
    if (existing) {
      console.log(`用户 ${username} 已存在`);
      process.exit(1);
    }
    
    // 加密密码
    const hashedPassword = await hashPassword(password);
    
    // 创建管理员用户
    const userId = utils.generateUUID();
    await query(
      `INSERT INTO users (id, username, password, nickname, is_admin, status)
       VALUES (?, ?, ?, ?, 1, 1)`,
      [userId, username, hashedPassword, '管理员']
    );
    
    console.log(`管理员用户创建成功！`);
    console.log(`用户名: ${username}`);
    console.log(`密码: ${password}`);
    console.log(`用户ID: ${userId}`);
    
    process.exit(0);
  } catch (error: any) {
    console.error('创建管理员用户失败:', error.message);
    process.exit(1);
  }
}

createAdmin();

